# import numpypy
import sys
from math import *

num_users = 2320895
num_items = 6095
num_genders = 3

def load_uapm( fname, minhit = 1 ):
    uapm = {}
    fi = open( fname, 'r' )
    for line in fi:
        arr = line.split()
        uid = int( arr[0] )        
        uapm[ uid ] = [ int(arr[1]), int(arr[2]) ]
    fi.close()
    return uapm
    
def write_value( fname, fin, ucat ):
    fi = open( fin, 'r' )
    fo = open( fname, 'w' )
    last_uid = -1
    fo.write( '2\n' )
    for line in fi:
        uid = int( line.split()[0] )
        if uid != last_uid:
            if uid in ucat:
                fo.write( '2 0:%d 1:%d\n' % (ucat[ uid ][0], ucat[ uid ][1] ) )
            else:
                fo.write( '0\n' )
            last_uid = uid
    fi.close()
    fo.close()

def write_percent( fname, fin, ucat ):
    fi = open( fin, 'r' )
    fo = open( fname, 'w' )
    last_uid = -1
    fo.write( '2\n' )
    for line in fi:
        uid = int( line.split()[0] )
        if uid != last_uid:
            if uid in ucat:
                sm = ucat[uid][0] + ucat[uid][1]
                if sm != 0:
                    fo.write( '2 0:%d 1:%f\n' % (sm, float(ucat[uid][0])/sm ) )
                else:
                    fo.write( '0\n' )
            else:
                fo.write( '0\n' )
            last_uid = uid
    fi.close()
    fo.close()


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'usage: <user.actwk> <train>'
        sys.exit(1)
    uapm = load_uapm( sys.argv[1] )    
    write_value  ( 'features/%s.uactwcntT' % sys.argv[2], sys.argv[2], uapm )
    write_percent( 'features/%s.uactwperT' % sys.argv[2], sys.argv[2], uapm )
